package com.onlinemusic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.onlinemusic.common.*;
import com.onlinemusic.mapper.ConsumerMapper;
import com.onlinemusic.pojo.domain.Consumer;
import com.onlinemusic.pojo.request.ConsumerPhoneCodeRequest;
import com.onlinemusic.service.ConsumerService;
import com.onlinemusic.service.LoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;


@Service
public class LoginServiceImpl implements LoginService {

    private static final String SMS_KEY_PREFIX = "sms:code:phone:"; //定义验证码key前缀
    private static final String MAIL_KEY_PREFIX = "mail:code:uuid:"; //定义验证码key前缀

    @Autowired
    private ConsumerService consumerService;

    @Autowired
    private ConsumerMapper consumerMapper;

    @Autowired
    private RedisUtil redis;

    @Autowired
    private EmailLinkUtil emailLinkUtil;

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @Override
    public R sendRCode(String phone) {
        //校验参数
        if (phone.matches("^1[3-9]\\d{9}$")) {
            try {
                //生成验证码
                Integer checkCode = RandomCodeGenerate.createCode(6);
                System.out.println(checkCode);
                //发送短信
                if (AliSmsUtil.sendMsgCode(phone, checkCode + "") != -1) {
                    //记录验证码 有效期5分钟 使用Redis存储 数据类型 String 存储：key: sms:code:phone:手机号 value：验证码
                    redis.set(SMS_KEY_PREFIX + phone, checkCode.toString(), 300);
                    //返回结果
                    return R.success("验证码发送成功");
                }
                return R.error("服务器异常，短信发送失败，请稍后重新尝试");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            return R.error("服务器异常，请联系管理员");
        }
        return R.error("手机号不合法，请填写正确的手机号");
    }

    /**
     * 验证短信验证码--Alice
     *
     * @param phoneCode
     * @return
     */
    @Override
    public R checkRCode(ConsumerPhoneCodeRequest phoneCode) {
        if (null != phoneCode) {
            if (!StringUtils.isBlank(phoneCode.getPhoneNum()) && !StringUtils.isBlank(phoneCode.getCheckCode())) {
                //取redis 校验是否存在验证码
                String codeInRedis = (String) redis.get(SMS_KEY_PREFIX + phoneCode.getPhoneNum());
                //过期返回提醒
                if (StringUtils.isBlank(codeInRedis)) {
                    return R.error("验证码已失效，请重新发送");
                    //与输入比对
                } else if (codeInRedis.equals(phoneCode.getCheckCode())) {
                    Consumer consumer = new Consumer();
                    BeanUtils.copyProperties(phoneCode, consumer);
                    //若新用户 设置默认数据 添加
                    if (!consumerService.existUserByPhone(phoneCode.getPhoneNum())) {
                        consumer.setUsername(phoneCode.getPhoneNum());
                        consumer.setAvatar("img/avatarImages/user.jpg");
                        consumer.setPassword("123456");
                        //如果不存在，创建用户对象并保存到数据库
                        if (consumerMapper.insert(consumer) < 0) {
                            return R.error("用户注册失败，请重试");
                        }
                    }
                    //登录成功后删除验证码
                    redis.del(SMS_KEY_PREFIX + phoneCode.getPhoneNum());
                    return R.success("注册成功，并登录", consumerMapper.selectList(new QueryWrapper<>(consumer)));
                } else {
                    return R.error("验证码错误");
                }
            }
            return R.error("不能提交空数据");
        }
        return R.fatal("服务器异常，请联系管理员");
    }

    /**
     * 发送邮箱
     *
     * @param recipientEmail
     * @param activationCode
     * @param message
     * @return
     */
    @Override
    public R sendMailCode(String recipientEmail, String activationCode, String message) {
        try {
            //调用Utils发送
            emailLinkUtil.sendActivationEmail(recipientEmail, activationCode);
            //存入redis
            redis.set(MAIL_KEY_PREFIX + recipientEmail, activationCode, 300);
            return R.success(message);
        } catch (Throwable e) {
            System.out.println("Failed to send activation email: " + e.getMessage());
        }
        return R.error("邮件发送失败");
    }

    /**
     * 验证邮箱code
     *
     * @param recipientEmail
     * @param code
     * @return
     */
    @Override
    public boolean checkMailCode(String recipientEmail, String code) {
        if (!StringUtils.isBlank(recipientEmail) && !StringUtils.isBlank(code)) {
            //校验是否存在验证码
            String codeInRedis = (String) redis.get(MAIL_KEY_PREFIX + recipientEmail);
            if (StringUtils.isBlank(codeInRedis)) {
                return false;
            } else if (codeInRedis.equals(code)) {
                //成功后删除验证码
                redis.del(MAIL_KEY_PREFIX + recipientEmail);
                return true;
            } else {
                return false;
            }
        }
        return false;
    }
}
